import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Row, 
  Col, 
  Statistic, 
  Table, 
  Tag, 
  Button, 
  Space,
  Alert,
  Progress
} from 'antd';
import { 
  ReloadOutlined, 
  CheckCircleOutlined, 
  ExclamationCircleOutlined,
  WarningOutlined 
} from '@ant-design/icons';
import api from '../services/authService';

const Monitoring: React.FC = () => {
  const [metrics, setMetrics] = useState({
    cpu_usage: 0,
    memory_usage: 0,
    disk_usage: 0,
    network_io: 0,
    deployment_success_rate: 0,
    average_deployment_time: 0
  });
  const [alerts, setAlerts] = useState([]);
  const [healthStatus, setHealthStatus] = useState({
    status: 'healthy',
    timestamp: '',
    services: {}
  });
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetchMonitoringData();
    const interval = setInterval(fetchMonitoringData, 30000); // 30秒刷新一次
    return () => clearInterval(interval);
  }, []);

  const fetchMonitoringData = async () => {
    setLoading(true);
    try {
      const [metricsRes, alertsRes, healthRes] = await Promise.all([
        api.get('/monitoring/metrics'),
        api.get('/monitoring/alerts'),
        api.get('/monitoring/health')
      ]);
      
      setMetrics(metricsRes.data);
      setAlerts(alertsRes.data.alerts || []);
      setHealthStatus(healthRes.data);
    } catch (error) {
      console.error('获取监控数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const getHealthStatusColor = (status: string) => {
    return status === 'healthy' ? 'success' : 'error';
  };

  const getAlertLevelColor = (level: string) => {
    const colors: { [key: string]: string } = {
      critical: 'red',
      warning: 'orange',
      info: 'blue'
    };
    return colors[level] || 'default';
  };

  const alertColumns = [
    {
      title: '级别',
      dataIndex: 'level',
      key: 'level',
      render: (level: string) => (
        <Tag color={getAlertLevelColor(level)}>
          {level.toUpperCase()}
        </Tag>
      ),
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '时间',
      dataIndex: 'created_at',
      key: 'created_at',
    },
  ];

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
        <h1>监控告警</h1>
        <Button 
          icon={<ReloadOutlined />} 
          onClick={fetchMonitoringData}
          loading={loading}
        >
          刷新
        </Button>
      </div>

      {/* 系统状态 */}
      <Card title="系统状态" style={{ marginBottom: 16 }}>
        <Alert
          message={`系统状态: ${healthStatus.status === 'healthy' ? '健康' : '异常'}`}
          type={getHealthStatusColor(healthStatus.status)}
          icon={healthStatus.status === 'healthy' ? <CheckCircleOutlined /> : <ExclamationCircleOutlined />}
          showIcon
        />
        <Row gutter={16} style={{ marginTop: 16 }}>
          {Object.entries(healthStatus.services || {}).map(([service, status]) => (
            <Col span={6} key={service}>
              <Card size="small">
                <Statistic
                  title={service}
                  value={status}
                  valueStyle={{ 
                    color: status === 'healthy' ? '#3f8600' : '#cf1322',
                    fontSize: '16px'
                  }}
                />
              </Card>
            </Col>
          ))}
        </Row>
      </Card>

      {/* 性能指标 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="CPU使用率"
              value={metrics.cpu_usage}
              suffix="%"
              valueStyle={{ color: metrics.cpu_usage > 80 ? '#cf1322' : '#3f8600' }}
            />
            <Progress 
              percent={metrics.cpu_usage} 
              size="small" 
              status={metrics.cpu_usage > 80 ? 'exception' : 'active'}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="内存使用率"
              value={metrics.memory_usage}
              suffix="%"
              valueStyle={{ color: metrics.memory_usage > 80 ? '#cf1322' : '#3f8600' }}
            />
            <Progress 
              percent={metrics.memory_usage} 
              size="small" 
              status={metrics.memory_usage > 80 ? 'exception' : 'active'}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="磁盘使用率"
              value={metrics.disk_usage}
              suffix="%"
              valueStyle={{ color: metrics.disk_usage > 80 ? '#cf1322' : '#3f8600' }}
            />
            <Progress 
              percent={metrics.disk_usage} 
              size="small" 
              status={metrics.disk_usage > 80 ? 'exception' : 'active'}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="网络IO"
              value={metrics.network_io}
              suffix="MB/s"
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 部署统计 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={12}>
          <Card>
            <Statistic
              title="部署成功率"
              value={metrics.deployment_success_rate}
              suffix="%"
              valueStyle={{ color: metrics.deployment_success_rate > 90 ? '#3f8600' : '#cf1322' }}
            />
            <Progress 
              percent={metrics.deployment_success_rate} 
              size="small" 
              status={metrics.deployment_success_rate > 90 ? 'active' : 'exception'}
            />
          </Card>
        </Col>
        <Col span={12}>
          <Card>
            <Statistic
              title="平均部署时间"
              value={metrics.average_deployment_time}
              suffix="分钟"
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 告警列表 */}
      <Card title="告警列表">
        <Table
          columns={alertColumns}
          dataSource={alerts}
          loading={loading}
          rowKey="id"
          pagination={false}
          size="small"
        />
      </Card>
    </div>
  );
};

export default Monitoring;
